package com.msb.mall.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.msb.common.dto.es.SkuESModel;
import com.msb.mall.mallsearch.config.MallElasticSearchConfiguration;
import com.msb.mall.mallsearch.constant.ESConstant;
import com.msb.mall.mallsearch.service.MallSearchService;
import com.msb.mall.mallsearch.vo.SearchParamVO;
import com.msb.mall.mallsearch.vo.SearchResult;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.lucene.util.QueryBuilder;
import org.apache.lucene.util.packed.PagedMutable;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.hibernate.validator.internal.engine.messageinterpolation.InterpolationTermType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
import java.util.stream.Collectors;

/**
 * @Author zhangjiajun
 * @Email zhangjiajun@hydsoft.com
 * @Description
 * @Date 2025/7/29 9:34
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParamVO param) {
        SearchResult result = null;

        //1. 准备检索的请求
        SearchRequest request = buildSearchRequset(param);

        //2. 执行
        try {
            SearchResponse response = client.search(request, MallElasticSearchConfiguration.COMMON_OPTIONS);

            //3. 封装检索信息为SearchResult
            result = buildSearchResult(response, param);
        } catch (Exception e) {

        }

        return result;
    }


    /**
     * 构建返回信息
     *
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParamVO param) {
        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();

        List<SkuESModel> esModels = new ArrayList<>();
        //1. 检索的所有商品信息
        SearchHit[] products = hits.getHits();
        if (products != null && products.length > 0) {
            for (SearchHit product : products) {
                String sourceAsString = product.getSourceAsString();
                //把json字符串转成SkuESModel
                SkuESModel model = JSON.parseObject(sourceAsString, SkuESModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    //设置高亮
                    HighlightField subTitle = product.getHighlightFields().get("subTitle");
                    String highlightText = subTitle.getFragments()[0].toString();
                    //设置高亮
                    model.setSubTitle(highlightText);
                }
                esModels.add(model);
            }
        }
        result.setProducts(esModels);


        Aggregations aggregations = response.getAggregations();
        //2. 当前商品所涉及的所有的品牌
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        //存储所有品牌的容器
        List<SearchResult.BrandVO> brandVOs = new ArrayList<>();
        if (buckets != null && buckets.size() > 0) {
            for (Terms.Bucket bucket : buckets) {
                SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
                //获取品牌的key
                String keyAsString = bucket.getKeyAsString();
                //设置品牌的编号
                brandVO.setBrandId(Long.parseLong(keyAsString));

                //然后需要获取品牌的名称和图片地址
                ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
                List<? extends Terms.Bucket> bucketsImg = brandImgAgg.getBuckets();
                if (bucketsImg != null && bucketsImg.size() > 0) {
                    String img = bucketsImg.get(0).getKeyAsString();
                    brandVO.setBrandImg(img);
                }
                //获取品牌名称的信息
                ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
                brandVO.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());

                brandVOs.add(brandVO);
            }
        }
        result.setBrands(brandVOs);

        //3. 当前商品涉及到的所有的类别信息
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> bucketsCatalogs = catalogAgg.getBuckets();
        //创建一个保存所有类别的容器
        List<SearchResult.CatalogVO> catalogVOs = new ArrayList<>();
        if (bucketsCatalogs != null && bucketsCatalogs.size() > 0) {
            for (Terms.Bucket bucket : bucketsCatalogs) {
                SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();

                String keyAsString = bucket.getKeyAsString();
                catalogVO.setCatalogId(Long.parseLong(keyAsString));

                //获取类别的名称
                ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
                String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
                catalogVO.setCatalogName(catalogName);

                catalogVOs.add(catalogVO);
            }
        }
        result.setCatalogs(catalogVOs);

        //4. 当前商品涉及到的所有的属性信息
        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> bucketsAttr = attrIdAgg.getBuckets();
        List<SearchResult.AttrVO> attrVOs = new ArrayList<>();
        if (bucketsAttr != null && bucketsAttr.size() > 0) {
            for (Terms.Bucket bucket : bucketsAttr) {
                SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
                String keyAsString = bucket.getKeyAsString();
                attrVO.setAttrId(Long.parseLong(keyAsString));

                //获取属性名称
                ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
                attrVO.setAttrName(attrName);

                //获取属性值
                ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
                if (attrValueAgg.getBuckets() != null && attrValueAgg.getBuckets().size() > 0) {
                    List<? extends Terms.Bucket> buck = attrValueAgg.getBuckets();
                    //todo 将查询到的多个属性值  拼接为一个集合
                    if (buck != null && buck.size() > 0) {
                        List<String> attrValues = buck.stream().map(e -> e.getKeyAsString()).collect(Collectors.toList());
                        attrVO.setAttrValues(attrValues);
                    }
                }

                attrVOs.add(attrVO);
            }
        }

        result.setAttrs(attrVOs);

        //5. 分页信息   当前页 总的记录数    总页数
        long total = hits.getTotalHits().value;
        //总的记录数
        result.setTotal(total);
        //当前页
        result.setPageNum(param.getPageNum());
        long totalPage = total % ESConstant.PRODUCT_PAGESIZE == 0 ? total / ESConstant.PRODUCT_PAGESIZE : (total / ESConstant.PRODUCT_PAGESIZE) + 1;
        //总页数
        result.setTotalPages((int) totalPage);

        List<Integer> navs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            navs.add(i);
        }
        result.setNavs(navs);
        return result;
    }


    /**
     * 构建检索的请求
     *
     * @param param 请求参数
     * @return
     */
    private SearchRequest buildSearchRequset(SearchParamVO param) {
        SearchRequest request = new SearchRequest();
        request.indices(ESConstant.PRODUCT_INDEX);

        SearchSourceBuilder builder = new SearchSourceBuilder();


        //构建具体的检索条件
        //1. 构建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        /**
         * "must": [
         *         {
         *           "match": {
         *             "subTitle": "华为"
         *           }
         *         }
         * ],
         */
        //1.1 1.1 关键字查询
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("subTitle", param.getKeyword()));
        }

        //1.2 类别
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }

        //1.3 品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        //1.4 是否有库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        //1.5 价格区间检索
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String _skuPrice = param.getSkuPrice();
            if (param.getSkuPrice().startsWith("_") || param.getSkuPrice().endsWith("_")) {
                _skuPrice = param.getSkuPrice().replace("_", "").trim();
            }
            if (!StringUtils.isEmpty(_skuPrice)) {
                String[] msg = _skuPrice.split("_");
                RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
                if (msg.length == 2) {
                    //200_300
                    skuPrice.gte(msg[0]).lte(msg[1]);
                } else if (msg.length == 1) {
                    // 200_   or  _300
                    if (param.getSkuPrice().startsWith("_")) {
                        // _300
                        skuPrice.lte(msg[0]);
                    }
                    if (param.getSkuPrice().endsWith("_")) {
                        // 200_
                        skuPrice.gte(msg[0]);
                    }

                }
                boolQuery.filter(skuPrice);
            }
        }

        // 1.6 属性的检索条件  attrs=20_8寸:10寸 & attrs=19_64G:128G
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder boolNestQuery = QueryBuilders.boolQuery();
                //attrs=20_8寸:10寸
                //分割
                String[] attrArray = attr.split("_");
                //属性编号
                String attrId = attrArray[0];
                //属性值  64G:128G
                String[] values = attrArray[1].split(":");

                //拼接组合条件
                boolNestQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolNestQuery.must(QueryBuilders.termsQuery("attrs.attrValue", values));

                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolNestQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        builder.query(boolQuery);

        // 2. 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], sortOrder);
        }

        //3. 分页
        if (param.getPageNum() != null) {
            //需要做一个分页计算
            // pageNum:1   from 0:  [0,1,2,3,4]
            // pageNum:2   from 5:  [5,6,7,8,9]
            //  from = (pageNum - 1) * pageSize
            builder.from((param.getPageNum() - 1) * ESConstant.PRODUCT_PAGESIZE);
            builder.size(ESConstant.PRODUCT_PAGESIZE);
        }

        //4. 设置高亮  --有关键字查询才需要高亮显示
        if (!StringUtils.isEmpty(param.getKeyword())) {

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("subTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        request.source(builder);

        //5.聚合
        //5.1 品牌的聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId");
        brandAgg.size(50);
        //品牌的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(10));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(10));
        builder.aggregation(brandAgg);

        //5.2 类别的聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId");
        catalogAgg.size(10);
        //类别子聚合
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(10));
        builder.aggregation(catalogAgg);

        //5.3 属性的聚合
        NestedAggregationBuilder nestedAttrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //属性id聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg");
        attrIdAgg.field("attrs.attrId");
        attrIdAgg.size(10);

        //属性id下子聚合    --名称和属性值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));
        nestedAttrAgg.subAggregation(attrIdAgg);


        builder.aggregation(nestedAttrAgg);


        System.out.println(builder.toString());

        return request;
    }
}
